﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using RStein.PosterousReader.WP.ViewModels.ViewObjects;
using RStein.Posterous.API;
using RStein.PosterousReader.WP.HostServices;
using RStein.PosterousReader.WP.Extensions;
using System.Threading;
using System.Diagnostics;
using RStein.PosterousReader.Common;

namespace RStein.PosterousReader.WP.ViewModels
{
    public class PostDetailViewModel : PosterousViewModelBase
    {
        private string m_postTextHeader;
        private PostVO m_selectedPost;
        private string m_postCommentsHeader;
        private bool m_isPostLoaded;
        private ICommand m_EditPostCommand;
        private IPosterousSite m_postSite;
        public static readonly string FINAL_EDIT_URL = "{0}?id={1}&site={2}";
        

        public PostDetailViewModel(IPosterousApplication posterousApplication, INavigationService navigation)
            : base(posterousApplication, navigation, GlobalConstants.PAGE_POST_DETAIL_TITLE)
        {
          EditPostCommand = new DelegateCommand<Object>(_ =>
                                                       {                                                         
                                                         Uri fullUrl = new Uri(String.Format(FINAL_EDIT_URL, GlobalConstants.PAGE_POST_EDIT_URI, SelectedPost.Id, PostSiteId), UriKind.Relative);
                                                         IsInvalidModel  = true;
                                                         NavigationService.Navigate(fullUrl);
                                                       },
                                                      _ => SelectedPost != null);
          
        }

        public int PostSiteId
        {
          get;
          set;
        }

        public ICommand EditPostCommand
        {
          get
          {
            return m_EditPostCommand;
          }

          set
          {
            m_EditPostCommand = value;
            RaisePropertyChangedEvent(() => EditPostCommand);
          }
        }

        public bool IsPostLoadingInProgress
        {
          get
          {
            return m_isPostLoaded;
          }
          set
          {
            m_isPostLoaded = value;
            RaisePropertyChangedEvent(() => IsPostLoadingInProgress);
          }

        }

        public string PostTextHeader
        {
            get
            {
                return m_postTextHeader;
            }            
            set
            {
                m_postTextHeader = value;
                RaisePropertyChangedEvent(() => PostTextHeader);
            }

        }

        public string PostCommentsHeader
        {
            get
            {
                return m_postCommentsHeader;
            }
            set
            {
                m_postCommentsHeader = value;
                RaisePropertyChangedEvent(() => PostCommentsHeader);
            }

        }
        public PostVO SelectedPost
        {
            get
            {
                return m_selectedPost;
            
            }
            set
            {
                m_selectedPost = value;
                RaisePropertyChangedEvent(() => SelectedPost);
            }
        }

        private void preparePost()
        {         
         
          IPosterousPost post = getPosterousPost();
          storeSite(post);

          if (post == null)
          {
            SelectedPost = null;
            return;
          }


          SelectedPost = new PostVO()
                          {
                            SynchContext = SynchronizationContext.Current,
                            Id = post.Id,
                            Body = String.Empty,
                            Title = post.Title
                            
                          };

          //Workaround for correct data binding
          SelectedPost.Body = post.Body;


          var commentsVO = from comment in post.Comments
                            select new CommentVO
                                        {
                                          SynchContext = SynchronizationContext.Current,
                                          Author = comment.Author.Name,
                                          Text = comment.Body,                                          
                                        };

          
          SynchContext.Send(_ => SelectedPost.Comments.AddRange(commentsVO), null);
          IsPostLoadingInProgress = false;                   
         }

        private void storeSite(IPosterousPost post)
        {
          PostSiteId = post.Site.Id;
        }

        private IPosterousPost getPosterousPost()
        {

          string idString = NavigationService.GetQueryParameter(GlobalConstants.OBJECT_ID_KEY);
              
          int id = int.Parse(idString.Trim());
          IPosterousAccount account = PosterousApplicatonService.GetOrAddCachedPosterousAccount(LastUsedUserName, LastUsedPassword);

          IPosterousPost currentPost = (from site in account.Sites
                                        from post in site.Posts
                                        where post.Id == id
                                        select post).FirstOrDefault();
          return currentPost;

        }

        protected override void DoInternalInit()
        {          
          IsPostLoadingInProgress = true;
          PostTextHeader = GlobalConstants.PAGE_POST_DETAIL_POST_HEADER;
          PostCommentsHeader = GlobalConstants.PAGE_POST_DETAIL_POST_COMMENTS_HEADER;          
          
        }
        
        protected override void DoInternalAsyncInit()
        {
          preparePost();
        }
      
        protected override bool IsAllInitDataLoaded()
        {
          return !IsPostLoadingInProgress;
        }

    }
}
